# -*- coding: utf-8 -*-
"""
CPU使用率监控器
动态调整指标计算频率，充分利用CPU资源
"""

import psutil
import threading
import time
import logging
from typing import Dict, Optional

class CPUMonitor:
    """CPU使用率监控器"""
    
    def __init__(self, check_interval=5):
        self.check_interval = check_interval
        self.current_cpu_usage = 0
        self.avg_cpu_usage = 0
        self.cpu_history = []
        self.max_history = 20  # 保留最近20次记录
        
        # CPU使用率阈值
        self.low_cpu_threshold = 30    # 低CPU使用率阈值
        self.high_cpu_threshold = 80   # 高CPU使用率阈值
        
        # 动态调整参数
        self.thread_multiplier = 1.0   # 线程数量乘数
        self.interval_multiplier = 1.0 # 计算间隔乘数
        
        self.monitoring = False
        self.monitor_thread = None
        
    def start_monitoring(self):
        """启动CPU监控"""
        self.monitoring = True
        self.monitor_thread = threading.Thread(target=self._monitor_worker, daemon=True)
        self.monitor_thread.start()
        logging.info("CPU监控已启动")
        
    def stop_monitoring(self):
        """停止CPU监控"""
        self.monitoring = False
        if self.monitor_thread:
            self.monitor_thread.join(timeout=1)
        logging.info("CPU监控已停止")
        
    def _monitor_worker(self):
        """CPU监控工作线程"""
        while self.monitoring:
            try:
                # 获取CPU使用率
                self.current_cpu_usage = psutil.cpu_percent(interval=1)
                
                # 更新历史记录
                self.cpu_history.append(self.current_cpu_usage)
                if len(self.cpu_history) > self.max_history:
                    self.cpu_history.pop(0)
                
                # 计算平均CPU使用率
                self.avg_cpu_usage = sum(self.cpu_history) / len(self.cpu_history)
                
                # 动态调整参数
                self._adjust_parameters()
                
                time.sleep(self.check_interval)
                
            except Exception as e:
                logging.error(f"CPU监控异常: {e}")
                time.sleep(self.check_interval)
                
    def _adjust_parameters(self):
        """根据CPU使用率动态调整参数"""
        if self.avg_cpu_usage < self.low_cpu_threshold:
            # CPU使用率低，可以增加计算频率
            self.thread_multiplier = min(2.0, self.thread_multiplier + 0.1)
            self.interval_multiplier = max(0.5, self.interval_multiplier - 0.05)
            logging.info(f"CPU使用率低({self.avg_cpu_usage:.1f}%)，增加计算频率")
            
        elif self.avg_cpu_usage > self.high_cpu_threshold:
            # CPU使用率高，减少计算频率
            self.thread_multiplier = max(0.5, self.thread_multiplier - 0.1)
            self.interval_multiplier = min(2.0, self.interval_multiplier + 0.05)
            logging.info(f"CPU使用率高({self.avg_cpu_usage:.1f}%)，减少计算频率")
            
    def get_optimal_thread_count(self, base_thread_count: int) -> int:
        """获取最优线程数量"""
        optimal_count = int(base_thread_count * self.thread_multiplier)
        return max(1, min(100, optimal_count))  # 限制在1-100之间
        
    def get_optimal_interval(self, base_interval: int) -> int:
        """获取最优计算间隔"""
        optimal_interval = int(base_interval * self.interval_multiplier)
        return max(1, optimal_interval)
        
    def get_cpu_stats(self) -> Dict:
        """获取CPU统计信息"""
        return {
            "current_cpu_usage": self.current_cpu_usage,
            "avg_cpu_usage": self.avg_cpu_usage,
            "thread_multiplier": self.thread_multiplier,
            "interval_multiplier": self.interval_multiplier,
            "is_low_cpu": self.avg_cpu_usage < self.low_cpu_threshold,
            "is_high_cpu": self.avg_cpu_usage > self.high_cpu_threshold
        }
        
    def should_increase_frequency(self) -> bool:
        """是否应该增加计算频率"""
        return self.avg_cpu_usage < self.low_cpu_threshold
        
    def should_decrease_frequency(self) -> bool:
        """是否应该减少计算频率"""
        return self.avg_cpu_usage > self.high_cpu_threshold
